package com.icebergteam.warfacewidget.wiki.data;

import java.util.regex.Pattern;

import org.apache.http.client.methods.HttpGet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.ContentValues;
import android.database.Cursor;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.R;
import com.icebergteam.warfacewidget.WidgetProvider;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.Pair;
import com.icebergteam.warfacewidget.core.asynctaskmanager.IHandleMessage;
import com.icebergteam.warfacewidget.core.asynctaskmanager.Task;
import com.icebergteam.warfacewidget.core.asynctaskmanager.TaskProgress;
import com.icebergteam.warfacewidget.core.connection.NetworkManager;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import com.icebergteam.warfacewidget.data.sql.WikiTable;
import com.icebergteam.warfacewidget.ui.YouTubeVideoPlayerActivity;

public class WikiDownloadTask extends Task{
	public static String className = WikiDownloadTask.class.getCanonicalName();
			private HttpGet request;
			Document doc;
			String noPreviewSrc = "http://i.imgur.com/VD8WAZG.png";
			String currentUrl;
			private boolean isCacheWikiHtml;
			private boolean isUpdateWikiHtml;
			private String fullHtml;
			
						
			public  WikiDownloadTask (TaskProgress message, IHandleMessage _handleError, String url, Boolean cache, Boolean update){
				super(message, _handleError);
			
				this.currentUrl = url;
				this.isCacheWikiHtml = cache;
				this.isUpdateWikiHtml = update;
			}
			
			private Pair<Boolean, String> getClearWikiHtml(String html, String urlBase) throws Exception{
				this.doc = Jsoup.parse(html);
				Boolean validWikiHtml = false;
				
				Elements content = this.doc.select("div#content").clone();
				
				if (!content.isEmpty()) {
					Element body = this.doc.body();
	
					content.attr(
							"style",
							"margin:0; float : none; padding: 10px; min-height:100%; ");
				

					content.select("div.wf_block").attr("style", "overflow-x:auto;");
					body.select(">*").remove();
					body.attr("style",
							"background:none;  font-size:14px; min-height:100%;");
					body.append(content.toString());
					LogManager.LogEA(WikiDownloadTask.className, "downloading thumbnails youtube videos");
					publishProgress(new TaskProgress(AppManager.getContext().getString(R.string.downloading_youtube_videos_thumbnails)));
					/*replace object to link with prev img*/
					Elements objects = this.doc.select("object, iframe");
					
					for (Element object : objects) {
						/*holder for video block*/
						Element holder = this.doc.createElement("div");
						holder.attr("style", "text-align:center;");
						holder.attr("class", "video");
						
						/*label video*/
						Element span = holder.appendElement("span");
						span.text("Click on the thumbnail to play video");
						span.attr("style","color:red; width: 100%; display:block");
					
						/*link to youtube video*/
						Element link = holder.appendElement("a");
						link.attr("class", "video-link");
						link.attr("style" ,"display:inline-block; position : relative;");
						link.attr("href", object.attr("data"));
					
						/*img prev video*/
						Element imgPrev = link.appendElement("img");
						imgPrev.attr("class", "video-prev");
						imgPrev.attr("style", "display:block;");
													
						String youtubeUrl="";
						if((youtubeUrl = YouTubeVideoPlayerActivity.getYoutubeUrl(object,true))!= null){
							LogManager.LogVA(WikiDownloadTask.className, youtubeUrl);	
														
							String src = YouTubeVideoPlayerActivity.getYoutubeVideoThumbnailByUrl(youtubeUrl);
							
							if(src == null){
								src = noPreviewSrc;
							}			
							imgPrev.attr("src", ((isCacheWikiHtml()) ? "file://": "") + ViewUtils.getSourcePath(src, WidgetProvider.WIKI_PATH, ViewUtils.TYPE_VIDEO, isCacheWikiHtml()));
							link.attr("href", youtubeUrl);
						}
						else{
							imgPrev.attr("src", ((isCacheWikiHtml()) ? "file://": "") + ViewUtils.getSourcePath(noPreviewSrc, WidgetProvider.WIKI_PATH, ViewUtils.TYPE_MEDIA, isCacheWikiHtml()));
							link.removeAttr("href"); 
							link.attr("onclick", String.format("javascript:window.droid.errorObjectTag()"));
						}
						object.empty();
						object.appendChild(holder);
						object.unwrap();
					}
					LogManager.LogEA(WikiDownloadTask.className, "downloading");
					publishProgress(new TaskProgress(AppManager.getContext().getString(R.string.downloading_resources)));
					
					/*replace src, href attributes to full url*/
					Elements media = this.doc.select("[src], [href]");
				
					String urlStr = NetworkManager.getCustomDomainLink(this.request.getURI().toURL().toString());
					
					for (Element src : media) {
						Pattern relativePathReg = Pattern.compile("^/");
						if (!src.attr("src").isEmpty()){
							if(relativePathReg.matcher(src.attr("src")).find()){
								src.attr("src", urlStr + src.attr("src"));
							}
							String srcAtrr = src.attr("src");
							String fullLocalUri = ViewUtils.getSourcePath(srcAtrr,  WidgetProvider.WIKI_PATH, ViewUtils.TYPE_MEDIA, isCacheWikiHtml);
							
							if(this.isCacheWikiHtml()){
								src.attr("src", "file://"+ fullLocalUri);
							}
						}
						else if (!src.attr("href").isEmpty() ){
							
							if(relativePathReg.matcher(src.attr("href")).find()){
								src.attr("href", urlStr + src.attr("href"));
								
								if(src.tagName().equals("link")){
									String fullLocalUri = ViewUtils.getSourcePath(src.attr("href"),  WidgetProvider.WIKI_PATH, ViewUtils.TYPE_VIDEO, isCacheWikiHtml());
									
									if(this.isCacheWikiHtml()){
										src.attr("href", "file://"+ fullLocalUri);
									}
								}
//								if(isWikiHtmlUrl(src.attr("href"))){
//								//	this.currentUrl = src.attr("href");
//									LogManager.LogEA(className, src.attr("href"));
//									SystemClock.sleep(2000);
//									getHtml(src.attr("href"), true);
//								}
							}
						}
					}
					validWikiHtml = true;
				}
				return new Pair<Boolean, String>(validWikiHtml, this.doc.toString());
			}
			
			public Pair<Boolean, String> getHtml(String url) throws Exception{
				Pair<Boolean, String> pair = this.isUpdateWikiHtml()? new Pair<Boolean, String>(false, null): restoreWiki(url);
				
				if(!pair.getFirst() || this.isUpdateWikiHtml()){
					pair = this.updateWiki(url);
					LogManager.LogVA(WikiDownloadTask.className, "update news", pair.getSecond().substring(0, 50));
				}
				return pair;
			}

			public boolean isCacheWikiHtml() {
				return this.isCacheWikiHtml;
			}

			public boolean isUpdateWikiHtml() {
				return this.isUpdateWikiHtml;
			}
			
			public void setUpdateWikiHtml(boolean set) {
				this.isUpdateWikiHtml = set;
			}
		
			@Override
			protected Integer doInBackground(String... params) {
				LogManager.LogEA(className, "start");
				Pair<Boolean,String> pair = null;
				int code = CODE_OK;
				try{
					
					
					if(this.isCancelled()) {
		      			  return CODE_CANCELED;
		      	  	}
					pair = getHtml(this.currentUrl);
								        	
					if(pair.getFirst() ){
						this.fullHtml = (pair.getSecond());
			        }
			        else{	
			           	throw new Exception("not contains html div#content " + getFullHtml().substring(0, 50));
			        }
			    }
				catch (final Exception exc){
			       	  try{
			       		  if(this.isCancelled()) {
			        		  return CODE_CANCELED;
			       		  }
			       		  pair = this.restoreWiki(this.currentUrl);
			       		 
			       		  if(pair.getFirst()){
			       			  this.fullHtml = (pair.getSecond());
			       			  code = CODE_OK;
			       			  handleMessage(null, AppManager.getContext().getString(R.string.restored_complete));
			       		  }
			       		  else{
			       			  code = CODE_ERROR;
			       			  handleError(null,exc.getMessage());
			       		  }
				          LogManager.LogEA(WikiDownloadTask.className, "not contains html main box", ViewUtils.getErrorMessage(exc));
				      }
			          catch(Exception exc2){
			        	  code = CODE_ERROR;
			        	  handleError(null,exc2.getMessage());
			          }
			      }
				  return code;
//				 for (int i = 20; i > 0; --i) {
//                     // Check if task is cancelled
//                     if (isCancelled()) {
//                             // This return causes onPostExecute call on UI thread
//                             return 1;
//                     }
//
//                     try {
//                             // This call causes onProgressUpdate call on UI thread
//                             publishProgress(new TaskProgress("asfdfsdfsdfsdfsdf", i*100/20));
//                             Thread.sleep(1000);
//                             
//                     } catch (InterruptedException e) {
//                             e.printStackTrace();
//                             // This return causes onPostExecute call on UI thread
//                             return 0;
//                     }
//                    
//                    
//             }
				
				 
//				 return 1;
			}
			
			
//			@Override
//			protected void onPostExecute(Integer _result) {
//				super.onPostExecute(_result);
//				LogManager.LogEA(className, currentUrl, WikiActivity.this.currentUrl, result);
//				if(super.result == CODE_ERROR){
//				
//				}
//			}

			public Object[] getOnCompleteParams() {
				return new Object[] {getFullHtml(), super.result, this.isUpdateWikiHtml};
			}
			
			public Pair<Boolean, String> updateWiki(String url) throws Exception {
				this.request = new HttpGet(url);
				Pair<Boolean, String> pair =  this.getClearWikiHtml(NetworkManager.getHtml(request), null);
				
				LogManager.LogVA(WikiDownloadTask.className, pair.getFirst(), this.isCacheWikiHtml());
				if(pair.getFirst() && isCacheWikiHtml()){
					ContentValues dataToInsert = new ContentValues();    
					dataToInsert.put(WikiTable.FIELD_URL, url);
					dataToInsert.put(WikiTable.FIELD_HTML, pair.getSecond());
				
					long id = AppManager.getDatabase().getWikiTable().updateOrInsert( dataToInsert);
					
					LogManager.LogVA(WikiDownloadTask.className, "save", id);
				}
				return pair;
			
			}
			
			public void abort(){
				if(this.request != null){
					this.request.abort();
				}
				this.cancel(true);
			}
			
			public Pair<Boolean, String> restoreWiki(String url) throws Exception{
				Cursor cursor = AppManager.getDatabase().getWikiTable().getWikiHtmlByUrl(url); 
				cursor.moveToFirst();
				int index = -1;
				
				String clearHtml = null;
				Boolean validWikiHtml = false;
				
				if(cursor != null && (index = cursor.getColumnIndex(WikiTable.FIELD_HTML.trim())) >=0 && cursor.getCount()> 0){
					clearHtml =  cursor.getString(index);
					validWikiHtml = (clearHtml == null || clearHtml != null && clearHtml.isEmpty()) ? false:true;
				}
				
				LogManager.LogVA(WikiDownloadTask.className, "restore wiki", (clearHtml != null) ? clearHtml.substring(0, 50):"");
				return new Pair<Boolean, String>(validWikiHtml, clearHtml);
			}

			public String getFullHtml() {
				return fullHtml;
			}

			
		}